package com.sunronsoft.mind.map;

import com.jfinal.config.*;
import com.jfinal.ext.handler.ContextPathHandler;
import com.jfinal.ext.interceptor.SessionInViewInterceptor;
import com.jfinal.json.FastJsonFactory;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import com.jfinal.server.undertow.UndertowServer;
import com.jfinal.template.Engine;

/**
 * @author Sunron
 **/
public class MainConfig extends JFinalConfig {

    public static Prop prop;
    private static UserService userService = UserService.getInstance();
    
    @Override
    public void configConstant(Constants me) {
        prop = PropKit.use("config.txt");

        me.setDevMode(prop.getBoolean("devMode", false));

        // Json配置
        me.setJsonFactory(FastJsonFactory.me());
        // 支持 Controller、Interceptor 之中使用 @Inject 注入业务层，并且自动实现 AOP
        me.setInjectDependency(true);
    }

    @Override
    public void configRoute(Routes me) {
        me.add("/", IndexController.class);
        me.add("/user", UserController.class, "/");
        me.add("/map", MindmapController.class, "/");
    }

    @Override
    public void configEngine(Engine me) {
        me.setDevMode(prop.getBoolean("engineDevMode", false));
        // 项目名称
        me.addSharedObject("projectName", prop.get("projectName", ""));
        me.addSharedObject("uploadUrl", prop.get("uploadUrl", "/upload"));
        me.addSharedObject("initialTreeDepth", prop.get("initialTreeDepth", "2"));
        me.addSharedObject("backgroundColor", prop.get("backgroundColor", "#fff"));
        me.addDirective("nowTime", NowTimeDirective.class);
        // 配置共享函数模板
        me.addSharedFunction("/common/_layout.html");
    }

    @Override
    public void configPlugin(Plugins me) {
        // 配置ehcache插件
        me.add(new EhCachePlugin());
    }

    @Override
    public void configInterceptor(Interceptors me) {
        // session
        me.add(new SessionInViewInterceptor());
        // 登录授权
        me.add(new AuthInterceptor());
    }

    @Override
    public void configHandler(Handlers me) {
        me.add(new ContextPathHandler("ctx"));
    }

    @Override
    public void onStart() {
        if (userService.list().isEmpty()) {
            userService.init();
        }

        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    public static void main(String[] args) {
        UndertowServer.start(MainConfig.class);
    }
}
